<?php

namespace adapters;

class FirePHP extends debug
{
	public function __construct()
	{
		core("File")->ImportScript(_SERVICES_DIR . "debug/FirePHP/FirePHP.class.php");
		//set_error_handler(array($this, "DebugErrorHandler"));
		$this->SetLib(new \FirePHP());
	}

	protected function Error($text = null, $title = null, $die = true)
	{
		if (!is_null($text))
		{
			$this->SetMessage($text);
		}

		if (!is_null($title))
		{
			$this->SetTitle($title);
		}

		$title = $this->GetTitle();
		$text = $this->GetMessage();

		$backtrace = $this->GetBackTrace();

		$this->lib->error($text, $title);

		$table   = array();
		$table[] = array('Action','File', 'Line');

		foreach ($backtrace as $item)
		{
			$location = "Unknown";
			if (!empty($item['file']))
			{
				$location = "$item[file]:$item[line]";
			}

			$table[] = array("$item[class]$item[type]$item[function]($item[args])", $item['file'], $item['line']);
		}

		$this->table('Backtrace', $table);


		if ($die)
		{
			die();
		}

		return true;
	}

	public function DbStats()
	{
		$table   = array();
		$table[] = array('Timing', 'Query', 'Result rows');

		$queries = service("db")->GetQueries();

		$total = 0;

		foreach ($queries as $item)
		{
			$total += $item['time'];
			$table[] = array($item['time'], $item['sql'], count($item['result']));
		}

		$this->table(count(service("db")->GetQueries()) .' queries ('.$total.'s)', $table);
	}

	public function GenericStats()
	{
		$this->info(core("Page")->GetCurrentPageName(), "page");
		$this->info(round(memory_get_peak_usage() / 1024 / 1024, 3), "Peak memory");
		$this->info($this->TimerCheckpoint(), "Generated in");
	}

	public function ComponentsStats()
	{
		$table   = array();
		$table[] = array('Component', 'Time');

		$components = $this->components;

		$total = 0;

		foreach ($components as $item)
		{
			$total += $item[1];
			$table[] = array($item[0], $item[1]);
		}

		$this->table(count($components) .' components ('.$total.'s)', $table);
		//core("debug")->info($compName."($time s)", "Component");
	}

	public function ServicesStats()
	{

	}
}